﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Components;
using Base;
using System.ComponentModel;
using Core.Base;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Data;
using Core;
using Core.Component;

namespace Core.Component
{
    public class SGVComboBox:ComboBox, ISGVControl, IBindingControl
    {
        public SGVComboBox()
            : base()
        {
            this.DoubleBuffered = true;
            this.DropDownStyle = ComboBoxStyle.DropDownList;
            this.CausesValidation = false;
            //this.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
            //this.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
            //this.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            //this.SetStyle(ControlStyles.UserPaint, true);

            this.GotFocus += new EventHandler(SGVComboBox_GotFocus);
            this.LostFocus += new EventHandler(SGVComboBox_LostFocus);
            this.KeyDown +=new KeyEventHandler(SGVComboBox_KeyDown);

            this.SelectedValueChanged += new EventHandler(SGVComboBox_SelectedValueChanged);
        }

        public Core.Component.UIComponent component
        {
            set;
            get;
        }

        void SGVComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if(this.DataBindings.Count > 0)
                this.DataBindings[0].WriteValue();

            if (module == null) return;

            module.CalcObject(module.entity.MainObject, this.BindingColumn);
        }

        void SGVComboBox_LostFocus(object sender, EventArgs e)
        {
            SGVControlHelper.ControlLostFocus(this);
        }

        void SGVComboBox_GotFocus(object sender, EventArgs e)
        {
            SGVControlHelper.ControlFocus(this);
        }

        void SGVComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4)
            {
                e.Handled = true;
            }
            if (e.KeyCode == Keys.F2)
            {
                this.DroppedDown = !this.DroppedDown;
            // e.Handled = true;
            }
            //this.SelectedValue
        }

        #region Border Custom
        //private Brush BorderBrush = new SolidBrush(SystemColors.Window);
        //private Brush ArrowBrush = new SolidBrush(SystemColors.ControlText);
        //private Brush DropButtonBrush = new SolidBrush(SystemColors.Control);
        //private Color _ButtonColor = SystemColors.Control;
        //public Color ButtonColor
        //{
        //    get { return _ButtonColor; }
        //    set
        //    {
        //        _ButtonColor = value;
        //        DropButtonBrush = new SolidBrush(this.ButtonColor);
        //        this.Invalidate();
        //    }
        //}

        //protected override void WndProc(ref Message m)
        //{
        //    base.WndProc(ref m);

        //    switch (m.Msg)
        //    {
        //        case 0xf:
        //            //Paint the background. Only the borders
        //            //will show up because the edit
        //            //box will be overlayed
        //            Graphics g = this.CreateGraphics();
        //            Pen p = new Pen(Color.White, 2);
        //            g.FillRectangle(BorderBrush, this.ClientRectangle);

        //            //Draw the background of the dropdown button
        //            Rectangle rect = new Rectangle(this.Width - 15, 3, 12, this.Height - 6);
        //            g.FillRectangle(DropButtonBrush, rect);

        //            //Create the path for the arrow
        //            System.Drawing.Drawing2D.GraphicsPath pth = new System.Drawing.Drawing2D.GraphicsPath();
        //            PointF TopLeft = new PointF(this.Width - 13, (this.Height - 5) / 2);
        //            PointF TopRight = new PointF(this.Width - 6, (this.Height - 5) / 2);
        //            PointF Bottom = new PointF(this.Width - 9, (this.Height + 2) / 2);
        //            pth.AddLine(TopLeft, TopRight);
        //            pth.AddLine(TopRight, Bottom);

        //            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //            //Determine the arrow's color.
        //            if (this.DroppedDown)
        //            {
        //                ArrowBrush = new SolidBrush(SystemColors.HighlightText);
        //            }
        //            else
        //            {
        //                ArrowBrush = new SolidBrush(SystemColors.ControlText);
        //            }

        //            //Draw the arrow
        //            g.FillPath(ArrowBrush, pth);

        //            break;
        //        default:
        //            break; // TODO: might not be correct. Was : Exit Select

        //            break;
        //    }
        //}

        ////Override mouse and focus events to draw
        ////proper borders. Basically, set the color and Invalidate(),
        ////In general, Invalidate causes a control to redraw itself.
        //#region "Mouse and focus Overrides"
        //protected override void OnMouseEnter(System.EventArgs e)
        //{
        //    base.OnMouseEnter(e);
        //    BorderBrush = new SolidBrush(SystemColors.Highlight);
        //    this.Invalidate();
        //}

        //protected override void OnMouseLeave(System.EventArgs e)
        //{
        //    base.OnMouseLeave(e);
        //    if (this.Focused)
        //        return;
        //    BorderBrush = new SolidBrush(SystemColors.Window);
        //    this.Invalidate();
        //}

        //protected override void OnLostFocus(System.EventArgs e)
        //{
        //    base.OnLostFocus(e);
        //    BorderBrush = new SolidBrush(SystemColors.Window);
        //    this.Invalidate();
        //}

        //protected override void OnGotFocus(System.EventArgs e)
        //{
        //    base.OnGotFocus(e);
        //    BorderBrush = new SolidBrush(SystemColors.Highlight);
        //    this.Invalidate();
        //}

        //protected override void OnMouseHover(System.EventArgs e)
        //{
        //    base.OnMouseHover(e);
        //    BorderBrush = new SolidBrush(SystemColors.Highlight);
        //    this.Invalidate();
        //}
        //#endregion 
        #endregion

        #region IBindingControl
        BaseModule module;

        String _bindingPropertyName = "SelectedValue";

        String _bindingTable;
        String _bindingColumn;
        String _dataSourceTable;
        String _dataSourceDisplayColumn;
        String _dataSourceKeyColumn;
        String _dataSourceColumns;
        String _sGVShortcutString = "F2: DUYỆT DANH SÁCH";
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public String SGVShortcutString
        {
            get { return _sGVShortcutString; }
            set { _sGVShortcutString = value; }
        }
        String _sGVTag;
        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string SGVTag
        {
            get
            {
                return _sGVTag;
            }
            set
            {
                _sGVTag = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        string IBindingControl.BindingPropertyName
        {
            get
            {
                return _bindingPropertyName;
            }
            set
            {
                _bindingPropertyName = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string BindingTable
        {
            get
            {
                return _bindingTable;
            }
            set
            {
                _bindingTable = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string BindingColumn
        {
            get
            {
                return _bindingColumn;
            }
            set
            {
                _bindingColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceTable
        {
            get
            {
                return _dataSourceTable;
            }
            set
            {
                _dataSourceTable = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceDisplayColumn
        {
            get
            {
                return _dataSourceDisplayColumn;
            }
            set
            {
                _dataSourceDisplayColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public string DataSourceKeyColumn
        {
            get
            {
                return _dataSourceKeyColumn;
            }
            set
            {
                _dataSourceKeyColumn = value;
            }
        }

        [CategoryAttribute(".SGV"), DescriptionAttribute("")]
        public String DataSourceColumns
        {
            get
            {
                return _dataSourceColumns;
            }
            set
            {
                _dataSourceColumns = value;
            }
        }

        

        #endregion

        public void RegisterModule(Core.Base.BaseModule module)
        {
            this.module = module;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.A))
            {
                this.SelectAll();
            }
            else if (keyData == Keys.Enter)
            {
                if(this.DroppedDown == false)
                    SendKeys.Send("{TAB}");
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }


        public void Init()
        {
            //this.DropDownStyle = ComboBoxStyle.DropDown;
            this.FlatStyle = System.Windows.Forms.FlatStyle.Standard;
            this.Font = new Font(AppContext.FontString, this.Font.Size + 0.3f, this.Font.Style);
            InitDataSource();
        }

        public virtual void InitDataSource()
        {
            try
            {
                if (String.IsNullOrEmpty(DataSourceTable)) return;

                if (DataSourceTable.ToUpper().Equals(AppContext.cstConstTableName.ToUpper()) == false)
                {

                    DataTable dt = AppContext.GetDataSource(DataSourceTable);
                    if (dt.Rows.Count > 0 && Convert.ToInt32(dt.Rows[0]["ID"]) != 0)
                    {
                        DataRow drDummy = dt.NewRow();
                        drDummy["ID"] = 0;
                        dt.Rows.InsertAt(drDummy, 0);
                    }
                    this.DataSource = dt;
                    this.ValueMember = DataSourceKeyColumn;
                    this.DisplayMember = DataSourceDisplayColumn;
                }
                else
                {
                    DataSet ds = AppContext.ConstCtrl.GetObjects(BindingColumn);
                    if (ds != null && ds.Tables.Count > 0)
                    {
                        DataTable dt = ds.Tables[0];
                        this.DataSource = dt;
                        this.ValueMember = AppContext.cstConstKey;
                        this.DisplayMember = AppContext.cstConstValue;
                    }
                }
            }
            catch (Exception ex)
            {
            }
            

            //this.Columns
        }


        public void UpdateFormat()
        {
        }

        public UIComponent Serialize()
        {
            UIComponent component = new UIComponent();
            SGVControlHelper.CreateUIComponentFromControl(component, this);

            if (component != null)
            {
                component.Value = this.Text;
            }
            return component;
        }

        public void Deserialize(UIComponent component)
        {
            throw new NotImplementedException();
        }
    }
}
